const ProductService = require('../../services/admin/ProductService');
const ProductController = {
  // 添加
  add: async (req, res) => {
    try {
      const result = await ProductService.add(req.body);
      if (!result) {
        res.send({
          success: false,
          code: 0,
          msg: '添加失败',
        });
      } else {
        res.send({
          success: true,
          code: 1,
          msg: '添加成功',
        });
      }
    } catch (error) {
      res.send({
        success: false,
        code: 0,
        msg: '添加失败' + error,
      });
    }
  },
  // 编辑
  edit: async (req, res) => {
    const { _id, ...data } = req.body;
    try {
      console.log(data, _id);
      const result = await ProductService.edit(_id, data);
      if (!result) {
        res.send({
          success: false,
          code: 0,
          msg: '编辑失败',
        });
      } else {
        res.send({
          success: true,
          code: 1,
          msg: '编辑成功',
        });
      }
    } catch (error) {
      res.send({
        success: false,
        code: 0,
        msg: '编辑失败' + error,
      });
    }
  },
  // 删除
  delete: async (req, res) => {
    const { _id } = req.body;
    try {
      const result = await ProductService.delete(_id);
      if (!result) {
        res.send({
          success: false,
          code: 0,
          msg: '删除失败',
        });
      } else {
        res.send({
          success: true,
          code: 1,
          msg: '删除成功',
        });
      }
    } catch (error) {
      res.send({
        success: false,
        code: 0,
        msg: '删除失败' + error,
      });
    }
  },
  // 列表
  list: async (req, res) => {
    try {
      const { page = 1, pageSize = 10 } = req.body;
      if (!page || !pageSize || page < 0) {
        res.send({
          success: false,
          code: 0,
          msg: '参数错误',
        });
        return;
      }
      const result = await ProductService.list(req.body);

      if (!result) {
        res.send({
          success: false,
          code: 0,
          msg: '查询失败',
        });
      } else {
        res.send({
          data: result,
          success: true,
          code: 1,
          msg: '查询成功',
        });
      }
    } catch (error) {
      res.send({
        success: false,
        code: 0,
        msg: '查询失败' + error,
      });
    }
  },
  // 查询
  findById: async (req, res) => {
    try {
      const { _id } = req.body;
      const result = await ProductService.findById(_id);
      if (result) {
        res.send({
          success: true,
          code: 1,
          msg: '查询成功',
          data: result,
        });
      } else {
        res.send({
          success: false,
          code: 0,
          msg: '查询失败',
        });
      }
    } catch (error) {
      res.send({
        success: false,
        code: 0,
        msg: '查询失败' + error,
      });
    }
  },
};
module.exports = ProductController;
